package person.xjl.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

//过滤器，servlet一个实现
@WebFilter(filterName ="loginFilter", urlPatterns = {"/Student/*","/Teacher/*"})
public class LoginFilter implements Filter {
    private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(
            Arrays.asList("", "/Student/login", "/logout", "/register","login.jsp")));
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        HttpSession session = httpServletRequest.getSession();
        //查用户的通行证
        Object obj = session.getAttribute("username");
        String path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()).replaceAll("[/]+$", "");

        // boolean loggedIn = (session != null && session.getAttribute("Id") != null);
        boolean allowedPath = ALLOWED_PATHS.contains(path);


        if(obj==null&&!allowedPath)
        {//用户没登录，并且请求是非法的，拒绝，回到登录页面
            httpServletRequest.getRequestDispatcher("/login.jsp").forward(request,response);
        }
        else
        {//用户登录过，或者请求的页面是合法，过滤器放行
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}